#include "sqlite3.h"
#include <string>
#include <cstdio>
#include <cstdlib>
#include "types.h"

int callback(void * not_used, int argc, char **argv, char **azColName){
    // callback for "select" sql
    // ATTENTION: every row <-> callback function
    int i;
    for(i=0; i<argc; i++){
        printf("\t%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
    }
    return 0;
}
void sql_connect(sqlite3 * &db)
{
    int rc;
    rc = sqlite3_open("dac.db", &db);
    if (rc)
    {
        fprintf(stderr, RED "[error] Can't open database: %s\n" NONE, sqlite3_errmsg(db));
        exit(0);
    }
    else
    {
        fprintf(stderr, CYAN "[init] Opened database successfully\n" NONE);
    }
}
void sql_close(sqlite3 * &db)
{
    sqlite3_close(db);
}
void sql_exec(sqlite3 * &db, void * tmp, const char * sql_format, ...)
{
    char *zErrMsg = 0;
    int rc;
    va_list argp;
    va_start(argp, sql_format);
    char *sql = sqlite3_vmprintf(sql_format, argp);
    va_end(argp);
    rc = sqlite3_exec(db, sql, callback, tmp, &zErrMsg);
    if (rc != SQLITE_OK)
    {
        fprintf(stderr, RED "[exec] SQL error: %s\n" NONE, zErrMsg);
        sqlite3_free(zErrMsg);
    }
    else
    {
        fprintf(stdout, CYAN "[exec] %s\n" NONE, sql);
    }
    sqlite3_free(sql);
}